// pages/order/order.js
import { CartModel } from '../../models/CartModel.js'
import { OrderModel } from '../../models/OrdelModel.js'
import { ProductModel } from '../../models/productModel.js'
import { AddressModel } from '../../models/AddressModel.js'
const  { Util } = require('../../utils/util.js') 
import Toast from '../../components/dist/toast/toast';
let util = new Util()
import { PaymentModel } from '../../models/PaymentModel.js'
let Payment = new PaymentModel()
let addressModel = new AddressModel()
let cartmodel = new CartModel()
let productModel = new ProductModel()
let orderModel = new OrderModel()
var App = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    products: [],
    account: [],
    userInfo: {},
    orderStatus: 0,
    oldOrder: false,
    orderId: '',
    addressList: [],
    default:false,
    totalPrice:0,
    from : '',//来自购物车还是商品直接购买
    orderData :{}
  },
  onShow:function(){
    this._updateAddress()
    this.isSelected()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._init()
    //购物车
    if (options.from == 'cart') {
    
      this.setData({
        'orderData.products': cartmodel.getCartDataFromLocal(true),
        'orderData.totalPrice':options.totalPrice,
        'orderData.status': 0,
        from :'cart'
      })
    } else if (options.from == 'product') {
      // let 获取商品信息
      productModel.getProductById(options.productId, res => {
        let product = res.result.data.data
        product.counts = options.count
        // product.count = parseInt(options.count)
        let newData = []
        newData.push(product);
        this.setData({
          'orderData.products': newData,
          'orderData.totalPrice': parseInt(options.count) * product.product_sell_price,
          'orderData.status': 0,
          from : 'product'
        })
      })
    }
    //旧订单
  },
  _init:function(){
    let openId = App.globalData.openId
    addressModel.getAddressList(openId,res=>{
      let addressList = res.result.data.data
      var i = 0
      for( ;i<addressList.length;i++ ){
        //如果已经设置了默认地址，则直接显示默认地址
        if(addressList[i].default){
          this.setData({
            address:addressList[i],
            default:true
          })
          console.log('存在默认地址',this.data.address,this.data.default)
        //否则提示：“请选择收货地址!”
         break;
        }
      }
      if(i==addressList.length){
        this.setData({
          default:false
        })
      }
      this.isSelected()
    })
  },
  _updateAddress:function(){
    if(JSON.stringify(this.data.address)==='{}'){
      console.log('address is null')
    }else{
      //更新address
      let addressId = this.data.address._id
      addressModel.getAddressById(addressId,res=>{
        let address = res.result.data.data
        this.setData({
          address:address
        })
    })
    }
  },

  isSelected:function(){
    let address = this.data.address
    if ( JSON.stringify(address)==='{}') {
      this.setData({
        default:false
      })
    }else{
      this.setData({
        default:true
      })
    }
  },
  selectAddress:function(){
    wx.navigateTo({
      url: '../address/selectAddress/selectAddress'
    })
  },
   //地址信息
  addressInfo: function (e) {
    if ("ok" == e.detail.status) {
      let address = {}
      let addressInfo = e.detail.addressInfo
      address.userName = addressInfo.userName
      address.phone = addressInfo.telNumber
      address.detailAddress = addressInfo.provinceName + addressInfo.cityName + addressInfo.countyName + addressInfo.detailInfo
      this.setData({
        address
      })
    }
  },
  // 从购物车中删除购买后的商品
  _delProductFromCart:function(){
    let products =this.data.products
    for(var i=0;i<products.length;i++){
      cartmodel._delete(products[i]._id)
    }
  },
  //点击立即购买
  confirm: function () {
    let that = this
    let address = that.data.address
    if ( JSON.stringify(address)==='{}') {
      that._showToast('none', '请选择地址')
      return
    }
    wx.getSetting({
      success: (res) => {
        //如果未登录
        if (!res.authSetting['scope.userInfo']) {
          wx.showModal({
            title: '授权提示',
            content: '下单需要在个人中心授权！',
            success(res) {
              wx.switchTab({
                url: '/pages/my/my'
              })
            }
          })
        }else{
          //用户已登录，完成支付
          let orderData = that.data.orderData
          orderData.address = that.data.address
          orderData.buyer_openId = App.globalData.openId
          
          that.paygo(orderData)
          //弹出提示框，“确认支付？”
          // Dialog.confirm({
          //   title: '确认支付',
          //   message: '抱歉，支付暂未开通！',
          // }).then(() => {
          //   //2、创建新订单
          //   orderModel.creat(orderData, res => {
          //     if (res.result.code == 0) {
          //       //如果订单创建成功
          //       console.log('新订单创建成功')
          //       // 删除对应购物车商品
          //       that._delProductFromCart()
          //     }
          //     wx.navigateBack({
          //       delta: 1,
          //     })
          //     })
          //   })
          //   .catch(() => {
          //     // 点击取消
          //   });
        }
      }
    }) 
  },
  //编辑收货地址
  editAddress:function(e){
    let addressId = e.detail.addressId
    wx.navigateTo({
      url: '../address/editAddress/editAddress?addressId='+addressId + '&isDelete=0',
    })
},
  // 订单详情
  productDetail: function (event) {
    let product_id = orderModel.getDataSet(event, "id")
    wx.navigateTo({
      url: '/pages/product/product?product_id=' + product_id,
    })
  },
  //支付
  paygo:function(orderData){
    let that = this
    let order = {
      orderId : util.uuid2(32,32),
      body : orderData.products[0].product_name,
      nonceStr : util.uuid2(32,32),
      money : orderData.totalPrice * 100,
    }
    console.log('order',order)
    Payment.unifiedOrder(order, res=>{
      console.log("获取支付参数成功", res)
      const payment = res.result.data.payment
      //调起支付
      wx.requestPayment({
        ...payment,
        success(res) {
          console.log('支付成功', res)
          orderModel.creat(orderData, res => {
            if (res.result.code == 0) {
              //如果订单创建成功
              console.log('新订单创建成功')
              // 如果购买商品来自购物车，删除对应购物车商品
              if(that.data.from == 'cart'){
                that._delProductFromCart()
              }
            }
            wx.switchTab({
              url: '../index/index',
            })
           })
        },
        fail(res) {
          Toast.fail('订单支付失败');
          console.error('支付失败', res)
        }
      })
    })
  },

 
})

